package com.sonny.ebook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.*;

public class BookKeeper {

	private File BaseFP;
	private final String profileFP = "BookKeeper.Properties";
	private String rarBinaryFP = "";
	private String srcRootFP = "";
	private String destRootFP = "";

	BookKeeper() {
	}

	public boolean deleteAllEmptySubFolder(File srcFP) {

		if (srcFP.exists()) {
			File[] files = srcFP.listFiles();
			if (files.length > 0) { // NOT EMPTY
				for (int i = 0; i < files.length; i++) {
					if (files[i].isDirectory())
						deleteAllEmptySubFolder(new File(files[i].getPath()));
				}
			}
			files = srcFP.listFiles();
			if (files.length == 0) {
				srcFP.delete();
				System.out.println("Deleted: " + srcFP.getPath());
			}
		}

		return true;
	}

	private boolean move2ParentFolder(File BaseFP, File file) {
		boolean result = false;

		// DO NOT MOVE TO PARENT FOLDER IF THE FILE IS ALREADY IN BASE FOLDER
		if (file.getParentFile().getPath().equalsIgnoreCase(BaseFP.getPath())) {
			result = true;
		} else {
			boolean chk = file.renameTo(new File(BaseFP, file.getName()));
			System.out.println("Moved: " + file.getParentFile().getPath());
			result = chk;
		}
		return result;
	}

	private int numberOfFilesInSameFormat(File folder, String ext) {
		int result = 0;
		File[] sub_files = folder.listFiles();
		for (int i = 0; i < sub_files.length; i++) {
			if (sub_files[i].getName().toLowerCase().endsWith(ext)) {
				result++;
			}
		}
		return result;
	}

	private void traverseFolderFiles(File folder, List<File> list) {
		if (folder.getName().endsWith(".EBook-DiGiBook") || folder.getName().endsWith("-rebOOk")) {

			String folderName = folder.getName();

			// TAG REMOVER
			
			
			folderName = folderName.replaceAll("RETAiL.EBook-DiGiBook", "");
			folderName = folderName.replaceAll(".RETAiL.eBOOk-rebOOk", "");
			folderName = folderName.replaceAll("-rebOOk", " ");
			folderName = folderName.replaceAll("ebook[A-z0-9_-]+", "");
			folderName = folderName.replaceAll(" -Mantesh", " ");
			folderName = folderName.replaceAll("-Slicer", " ");
			folderName = folderName.replaceAll("eBook-iNTENSiTY", " ");
			folderName = folderName.replaceAll("retail ebook distribution", " ");
			folderName = folderName.replaceAll("RETAiL eBOOk", " ");
			folderName = folderName.replaceAll("eBook DDU", " ");
			
			
			// CLEANER
			folderName = folderName.replaceAll("\\.", " ");
			folderName = folderName.replaceAll("\\_", " ");
			folderName = folderName.replaceAll("\\-", " ");

			File[] sub_files = folder.listFiles();
			for (int i = 0; i < sub_files.length; i++) {
				if (sub_files[i].isFile()) {

					if (sub_files[i].getName().toLowerCase().endsWith(".pdf")) {
						boolean chk = sub_files[i].renameTo(new File(sub_files[i].getParentFile().getPath() + "\\"
								+ folderName + ".pdf"));
						System.out.println("RENAMED: " + sub_files[i].getParentFile().getPath() + ".pdf");
					}
				}
			}
		}

		File[] sub_files = folder.listFiles();
		for (int i = 0; i < sub_files.length; i++) {
			if (sub_files[i].isFile()) {
				boolean isSuccess = true;
				String sub_FP = sub_files[i].getName().toLowerCase();

				if (sub_FP.endsWith(".txt")) {
					isSuccess = sub_files[i].delete();
				}
				if (sub_FP.endsWith(".htm")) {
					isSuccess = sub_files[i].delete();
				}
				if (sub_FP.endsWith(".html")) {
					isSuccess = sub_files[i].delete();
				}
				if (sub_FP.endsWith(".jpg")) {
					isSuccess = sub_files[i].delete();
				}
				if (sub_FP.endsWith(".gif")) {
					isSuccess = sub_files[i].delete();
				}
				if (sub_FP.endsWith(".diz")) {
					isSuccess = sub_files[i].delete();
				}
				if (sub_FP.endsWith(".nfo")) {
					isSuccess = sub_files[i].delete();
				}
				if (sub_FP.endsWith(".url")) {
					isSuccess = sub_files[i].delete();
				}
				if (sub_FP.endsWith(".!ut")) {
					isSuccess = sub_files[i].delete();
				}
				
				
				if (sub_FP.endsWith(".pdf")) {
					if (numberOfFilesInSameFormat(folder, ".pdf") == 1)
						isSuccess = move2ParentFolder(BaseFP, sub_files[i]);
				}

				if (sub_FP.endsWith(".epub")) {
					if (numberOfFilesInSameFormat(folder, ".epub") == 1)
						isSuccess = move2ParentFolder(BaseFP, sub_files[i]);
				}

				if (sub_FP.endsWith(".chm")) {
					if (numberOfFilesInSameFormat(folder, ".chm") == 1)
						isSuccess = move2ParentFolder(BaseFP, sub_files[i]);
				}

				if (sub_FP.endsWith(".djvu")) {
					if (numberOfFilesInSameFormat(folder, ".djvu") == 1)
						isSuccess = move2ParentFolder(BaseFP, sub_files[i]);
				}

				if (sub_FP.endsWith(".mobi")) {
					if (numberOfFilesInSameFormat(folder, ".mobi") == 1)
						isSuccess = move2ParentFolder(BaseFP, sub_files[i]);
				}

				// ARCHIVE HANDLER
				if (sub_FP.endsWith(".zip") || sub_FP.endsWith(".rar")) {
					isSuccess = uncompress_process(sub_files[i].getPath(), sub_files[i].getParentFile().getPath());
					isSuccess = sub_files[i].delete();
				}

				// IF RAR FILE HAS BEEN HANDLED, REMOVE r01, r02, r03 etc.
				if (sub_FP.matches("[A-z0-9_-]+.r[0-9][0-9]")) {
					if (numberOfFilesInSameFormat(folder, ".rar") == 0)
						isSuccess = sub_files[i].delete();
				}

				if (!isSuccess) {
					System.out.format("Failed file: %20s", sub_FP);
				}
			}
		}
		folder.setReadOnly();
		System.out.println("--: " + folder.getPath());
		File[] files = folder.listFiles();

		for (int j = 0; j < files.length; j++) {
			list.add(files[j]);
			if (files[j].isDirectory())
				traverseFolderFiles(files[j], list);
		}
	}

	// UNCOMPRESS ALL ZIP AND RAR ON THE SAME FOLDER
	private boolean uncompress_process(String srcFP, String destFP) {
		boolean result = true;
		File srcArchiveFile = new File(srcFP);

		if (srcArchiveFile.getName().toLowerCase().endsWith(".zip")) {
			CompressTools.unzip(srcArchiveFile.getPath(), destFP);
		} else if (srcArchiveFile.getName().toLowerCase().endsWith(".rar")) {
			CompressTools.unrar(rarBinaryFP, "x", srcArchiveFile.getPath(), destFP);
		}

		return result;
	}

	public void execute() {
		List<File> list = new ArrayList<File>();

		/*
		 * IN ORDER TO HANDLE EMBEDED ZIP FILEs, IT IS REQUIRED TO RUN THE
		 * FOLLOWING ROUTINES 3 TIMES IN A ROW
		 */
		for (int i = 0; i < 3; i++) {
			traverseFolderFiles(BaseFP, list);
			deleteAllEmptySubFolder(BaseFP);
			System.out.println("list.size = " + list.size());
		}
	}

	/**
	 * Initiate variables from Properties
	 */
	private void Init() {
		Properties properties = new Properties();
		try {
			String profileFP = "X:\\dev\\workspace\\personal\\EBookCleaner\\BookKeeper.properties";
			properties.load(new FileInputStream(profileFP));

			rarBinaryFP = properties.getProperty("rarBinaryFP");
			srcRootFP = properties.getProperty("srcRootFP");
			destRootFP = properties.getProperty("destRootFP");

			properties.list(System.out);

			File destFolder = new File(destRootFP);
			if (!destFolder.exists()) {
				destFolder.mkdir();
			}

			BaseFP = new File("X:\\[ docdoc ]");
			// BaseFP = new File("Z:\\[ eBooks ]\\[docdoc]");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {

		BookKeeper bookkeeper = new BookKeeper();
		bookkeeper.Init();
		bookkeeper.execute();
	}

}
